@page "/"
@page "/Login"

@using BootstrapBlazorApp.Server.Pojo
@inject AuthenticationStateProvider AuthenticationStateProvider
@layout LoginLayout
@inject AjaxService AjaxService
@inject SwalService SwalService
@inject NavigationManager NavigationManager

@attribute [AllowAnonymous]
<div >

    <div class="login-item login-item-gitee">
        <div class="login-header">
            <span>登录</span>
            <div class="login-register">没有账号？<a href="/Register">点此注册</a></div>
        </div>
        <ValidateForm Model="@LoginVo" OnValidSubmit="OnValidSubmit">
            <FloatingLabel DisplayText="用户名" @bind-Value="LoginVo.UserName" IsGroupBox="true" PlaceHolder="请输入用户名" />
            <FloatingLabel DisplayText="密码" @bind-Value="LoginVo.Password" type="password" IsGroupBox="true" PlaceHolder="请输入密码" />
            <div class="login-sms">
                <Checkbox TValue="bool" ShowLabel="false" ShowAfterLabel="true" DisplayText="记住我" />
            </div>
            <Button Text="登录" ButtonType="ButtonType.Submit" style="background-color: rgba(224,221,250,0.86);color: #444444;border-color: rgba(236,224,238,0.95)"></Button>
        </ValidateForm>
    </div>
</div>
@code
{
    private LoginVo LoginVo { get; set; } = new LoginVo();

    private async Task OnValidSubmit(EditContext arg)
    {
        StateHasChanged();
        try
        {
            var document = await AjaxService.InvokeAsync(new AjaxOption()
            {
                Url = "/api/Account/Login",
                Data = LoginVo
            });
        
            if (document?.RootElement.GetProperty("code").GetInt32() == 200)
            {
                await AjaxService.Goto("/HomePage"); //交换cookie
            }
            else
            {
                await SwalService.Show(new SwalOption()
                {
                    Category = SwalCategory.Error,
                    Content = document?.RootElement.GetProperty("message").GetString() ?? "系统异常",
                    Title = "登录失败"
                });
            }
        }
        catch (Exception ex)
        {
            // 处理网络请求或其他异常
            await SwalService.Show(new SwalOption()
            {
                Category = SwalCategory.Error,
                Content = "发生错误：" + ex.Message,
                Title = "系统错误"
            });
        }
    }

    

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        var user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;
        if (user?.Identity?.IsAuthenticated == true)
        {
            NavigationManager.NavigateTo("/HomePage");
        }
    }
}